package com.icoolkj.security.springmvc.interceptor;

import com.icoolkj.security.springmvc.vo.UserVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author icoolkj
 * @version 1.0
 * @description 拦截器实现权限控制
 * @createDate 2025/02/07 08:57
 */
@Component
public class SimpleAuthenticationInterceptor implements HandlerInterceptor {

    // 调用方法之前调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在这个方法中校验用户请求的 url 是否在用户的权限范围内
        // 取出用户身份信息
        Object object = request.getSession().getAttribute(UserVO.SESSION_USER_KEY);
        if (object == null) {
            // 没有认证，提示登录
            writeContent(response, "请登录");
        }

        UserVO userVO = (UserVO) object;
        // 请求的 url
        String requestURI = request.getRequestURI();
        if (userVO.getAuthorities().contains("p1") && requestURI.contains("r/r1")) {
            return true;
        }

        if (userVO.getAuthorities().contains("p2") && requestURI.contains("r/r2")) {
            return true;
        }

        writeContent(response, "没有权限，拒绝访问");

        return false;
    }

    private void writeContent(HttpServletResponse response, String msg) {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        writer.print(msg);
        writer.close();

        response.resetBuffer();
    }
}
